package com.yangye.wechat.controller;

import com.yangye.wechat.constants.Constants;
import com.yangye.wechat.service.CoreService;
import com.yangye.wechat.utils.MessageResponseUtil;
import com.yangye.wechat.utils.MessageUtil;
import com.yangye.wechat.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by Young.Y.Yang on 2018/5/10
 */
@Controller
@RequestMapping("/api/wechat/")
@Slf4j
public class WechatController {

	@Autowired
	private CoreService coreService;

	@RequestMapping(value = "/sign", method = RequestMethod.GET)
	@ResponseBody
	public String signature (HttpServletRequest request) {
		try {
			String signature = request.getParameter("signature"); // 微信加密签名
			String timestamp = request.getParameter("timestamp"); // 时间戳
			String nonce = request.getParameter("nonce");// 随机数
			String echostr = request.getParameter("echostr");// 随机字符串

			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				return echostr;
			} else {
				log.error("不是微信服务器发来的请求,请小心!");
				return null;
			}
		} catch (Exception e) {
			log.error("failed to check signature, cause:{}", e.getMessage());
			return null;
		}
	}

	@RequestMapping(value = "/sign", method = RequestMethod.POST)
	@ResponseBody
	String signature (HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");  //微信服务器POST消息时用的是UTF-8编码，在接收时也要用同样的编码，否则中文会乱码；
		response.setCharacterEncoding("UTF-8"); //在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
		String responseMessage = coreService.processRequest(request);
		log.info("response: " + responseMessage);
		return responseMessage;
	}
}
